import { 
  AmbientLight,
  AnimationAction,
  AnimationMixer,
  BoxGeometry,
  Clock,
  Color,
  IcosahedronGeometry,
  Mesh,
  MeshLambertMaterial,
  MeshPhongMaterial,
  MeshStandardMaterial,
  PerspectiveCamera,
  PlaneGeometry,
  PointLight,
  RepeatWrapping,
  Scene, 
  SphereGeometry, 
  SpotLight, 
  SpotLightHelper, 
  Texture, 
  TextureLoader, 
  Vector2, 
  WebGLRenderer
} from "three";
import stats from '../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GUI } from 'dat.gui';

let scene = new Scene();
let renderer = setRenderer();
let camera = setCamera();

const controls = {
  normalScaleX: 1,
  normalScaleY: 1,
  rotationSpeed: 0.01
}

let light = setLight();
let { sphere } = init();
addGUI();

const trackballControls = new OrbitControls(camera, renderer.domElement);
// 调整场景位置
trackballControls.target.set(0, 3, 0);

function render() {
  stats.update();
  trackballControls.update();

  sphere.rotation.y += controls.rotationSpeed;

  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
render();

function setRenderer() {
  const renderer = new WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 支持阴影生成 
  renderer.shadowMap.enabled = true;
  document.body.appendChild(renderer.domElement);

  return renderer
}

function setCamera(): PerspectiveCamera {
  let camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
  camera.position.set(0, 20, 40);
  scene.add( camera );

  return camera;
}

// 灯光设置
function setLight() {
  let spotLight = new SpotLight(0xffffff);
  spotLight.position.set(-10, 30, 40);
  spotLight.shadow.mapSize.width = 2048;
  spotLight.shadow.mapSize.height = 2048;
  spotLight.shadow.camera.fov = 15;
  spotLight.decay =2;
  spotLight.penumbra = 0.05;
  spotLight.castShadow = true;
  // spotLight.intensity = 0.1;

  scene.add(spotLight);

  return spotLight;
}

/** 功能区 */
function init() {
  let textureLoader = new TextureLoader();

  let material = new MeshPhongMaterial({
    map: textureLoader.load('/textures/earth/Earth.png'),
    normalMap: textureLoader.load('/textures/earth/EarthNormal.png'),
    // 高光贴图
    specularMap: textureLoader.load('/textures/earth/EarthSpec.png'),
    normalScale: new Vector2(10, 10)
  })

  // 创建球
  let sphereGeom = new SphereGeometry(10, 180, 180);
  let sphere = new Mesh(sphereGeom, material);
  scene.add(sphere);

  return { sphere }
}


function addGUI(): void {
  const gui = new GUI();  

  gui.add(light, 'intensity', 0, 1).name('光照亮度');
  gui.add(controls, 'rotationSpeed', -0.1, 0.1).name('旋转速度');
}